#include "notewidget.h"
#include "ui_notewidget.h"
#include <QStringListModel>

NoteWidget::NoteWidget(QWidget *parent)
    : QWidget(parent), ui(new Ui::NoteWidget), noteMapper(new NoteMapper)
{
    ui->setupUi(this);
    this->setWindowTitle("备忘签");
    ui->alarmClock->setDisplayFormat("yyyy-MM-dd hh:mm:ss");
    ui->alarmClock->setDateTime(QDateTime::currentDateTime());
    ui->alarmClock->setCalendarPopup(true);

    ui->noteListView->setEditTriggers(QAbstractItemView::NoEditTriggers);

    QStringListModel *model = new QStringListModel(this);

    ui->noteListView->setModel(model);

    QStringList items;

    QList<Note> ns = noteMapper->queryAllNotes();

    foreach (const auto &n, ns) {
        QString s;
        items << n.alarmClock + ">";
        s.append(QString("(%0)提醒:").arg(n.past ? "过期" : "未来"));
        s.append(n.content);

        items << s;
    }

    model->setStringList(items);
}

NoteWidget::~NoteWidget()
{
    delete ui;
    delete noteMapper;
}

void NoteWidget::on_addNote_clicked()
{
    Note n;
    QString now = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QString alarm = ui->alarmClock->dateTime().toString("yyyy-MM-dd hh:mm:ss");
    n.past = alarm.compare(now) ? false : true;
    n.exists = false;
    n.content = ui->noteContent->toPlainText();
    n.alarmClock = alarm;
    n.createTime = now;

    noteMapper->saveNote(n);

    updateListView();

    emit newNoteIntoTable();
}

void NoteWidget::updateListView()
{
    auto m = qobject_cast<QStringListModel *>(ui->noteListView->model());

    QStringList items;

    QList<Note> ns = noteMapper->queryAllNotes();

    foreach (const auto &n, ns) {
        QString s;
        items << n.alarmClock + ">";

        s.append(QString("(%0)提醒:").arg(n.past ? "过期" : "未来"));
        s.append(n.content);

        items << s;
    }

    m->setStringList(items);
}
